package model;

import controller.Calculator;

/**
 * @author Alexander Müller
 * 
 */
public class IPAddress {

	private String address = Constants.EMPTY, additionalInfo;
	private Octet[] addressBits = new Octet[4];


	public IPAddress(String address) {
		this.address = address;
		convertAddressToOctets();


	}

	public IPAddress(Octet[] addressBits) {
		this.addressBits = addressBits;
		convertBinaryOctetsToAddress();

	}

	public IPAddress(String address, String info) {
		this.address = address;
		convertAddressToOctets();
		additionalInfo = info;

	}

	public IPAddress(Octet[] addressBits, String info) {
		this.addressBits = addressBits;
		convertBinaryOctetsToAddress();
		additionalInfo = info;

	}

	public Octet[] getAddressBits() {
		return addressBits;
	}

	public Octet getAddressBits(int i) {
		return addressBits[i];
	}

	public void setOctet(Octet bits, int octetNumber) {
		addressBits[octetNumber] = bits;
	}

	public void setAddressBits(Octet[] addressBits) {
		this.addressBits = addressBits;
	}

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String getAdditionalInfo() {
		return additionalInfo;
	}

	public void setAdditionalInfo(String additionalInfo) {
		this.additionalInfo = additionalInfo;
	}

	private void convertAddressToOctets() {
		String[] splited = address.split(Constants.POINTPATTERN);
		for (int i = 0; i < splited.length; i++) {
			String converted = Calculator.getInstance().convertDecimalToBinary(
					Integer.parseInt(splited[i]));
			addressBits[i] = new Octet(converted);
		}
	}

	private void convertBinaryOctetsToAddress() {
		for (int i = 0; i < addressBits.length; i++) {
			if (i == 3) {
				address += addressBits[i].getBitValue();
			} else {
				address += addressBits[i].getBitValue() + Constants.POINT;
			}
		}
	}

}
